<?php

class RegistrasiModel{
	private $db;
	private $subbagian;
	
	private $validColumn;

	private $data;

	private $result;

	private $sort_by;
	private $sort_order;

	private $search_keyword;
	private $search_field;

	private $limit;
	
	function RegistrasiModel($dbObject){
		$this->subbagian 	= 'registrasi';		
		$this->db 			= $dbObject;

		$this->validColumn  = array(
			'username', 
			'password', 
			'subbagian', 
			'role'
		);
		
		// settting up configuration
		if(($this->start=$this->getGET('start')) == NULL)
			$this->start = 0;

		$this->sort_by 			= $this->getGET('sort_by');
		$this->sort_order 		= $this->getGET('sort_order');
		$this->search_keyword	= $this->getGET('search_keyword');
		$this->search_field		= $this->getGET('search_field');

		if(($this->limit=$this->getGET('limit')) == NULL)
			$this->limit = 50;		
	}
	
	private function getGET($param){
		if( isset( $_GET[$param] ) && $_GET[$param] != '' )
			return $_GET[$param];
		else
			return NULL;
	}
	
	public function countAll(){
		$where = $this->prepareWhereClause();	
			
		$q = "SELECT COUNT(*) FROM `caramel_managerial`.`user_account` $where";
		
		$this->total_record = $this->db->get_var($q);
		
		return $this->total_record;
	}	
	
	private function prepareWhereClause(){
		$where = '';
		if( $this->search_keyword && $this->search_field ){
			switch($this->search_field){
					case 'role_detail':
						$where = "WHERE `id` IN (SELECT `account_id` FROM `caramel_managerial`.`user_role` WHERE `subbagian`='".$this->search_keyword."')";
						break;
					default:
						$where = "WHERE ".$this->search_field."='".$this->search_keyword."'";
			}
		}
		
		return $where;
	}
	
	private function getDetailRegistrasi($id){
		$q = "SELECT `subbagian`, `role` FROM `caramel_managerial`.`user_role` WHERE `account_id`='".$id."'";
		
		$result = array();
		$r = $this->db->get_results($q, ARRAY_A);
		if( $r )	
			foreach($r as $j) $result[] = $j;
		
		return $result;
	}
	
	
	public function search(){			
		$where = $this->prepareWhereClause();
		
		// get data
		if( $this->sort_by )
			$q = "
			SELECT
				`id`, `username`, `password`
			FROM `caramel_managerial`.`user_account`
			$where
			ORDER BY `".$this->sort_by."` ".$this->sort_order." LIMIT ".$this->start.",".$this->limit."";
		else
			$q = "
			SELECT
				`id`, `username`, `password`
			FROM `caramel_managerial`.`user_account`
			$where
			LIMIT ".$this->start.",".$this->limit."";
		
		$this->result = $this->db->get_results($q, ARRAY_A);
		// detail
		if( count($this->result) > 0 ){
			foreach($this->result as &$r){
				$r['role_detail'] = $this->getDetailRegistrasi($r['id']);
			}
		}
		return $this->result;
	}

	public function getResult(){
		return $this->result;
	}

	function format($data){
		$result = array();
		foreach($this->validColumn as $v){
			if( isset($data[$v]) )
				$result[$v] = $data[$v];
			else
				$result[$v] = NULL;
		}
		
		return $result;
	}
	
	private function insertRegistrasi(){
		$query = "INSERT INTO `caramel_managerial`.`user_account` (`username`, `password`) VALUES ('".$this->data['username']."','".$this->data['password']."')";
		$this->db->query($query);
		
		$id = $this->db->get_var("SELECT MAX(`Id`) FROM `caramel_managerial`.`user_account`");
		return $id;
	}
	
	private function insertAccountRole($id){
		$dataAccount = array();
		$accountColumn = array(
			'subbagian', 
			'role'
		);
		
		// copy dari $data ke $dataAccount
		foreach($accountColumn as $c){
			$dataAccount[$c] = $this->data[$c];
		}
		
		if( count($dataAccount['subbagian']) > 0 ){
		
			$qHeader = "(`account_id`, `subbagian`, `role`)";			
			$query   = "INSERT INTO `caramel_managerial`.`user_role` ".$qHeader." VALUES ";
			$temp    = '';
			// looping through all material
			for($i=0; $i<count($dataAccount['subbagian']); $i++){			
				$qBody   = "('".$id."', '".$dataAccount['subbagian'][$i]."', '".$dataAccount['role'][$i]."')";
				$temp[]  = $qBody;
			}
			
			$query .= implode($temp, ",").';';
			
			$this->db->query($query);
		}
	}
	
	function put($data){		
		$this->data	= $this->format($data);// buang field2 yang tidak dibutuhkan
		
		if( $this->isExist() == FALSE ){				
			// registrasi
			$id = $this->insertRegistrasi();

			// account
			$this->insertAccountRole($id);					
		}
		else{
			return INSERT_FAIL_DUPLICATE;
		}
	}
	
	function isExist(){
		$query = "SELECT COUNT(*) FROM `caramel_managerial`.`user_account` WHERE `username`='".$this->data['username']."'";
		$count = $this->db->get_var($query);
		
		if( $count > 0 )
			return TRUE;
			
		return FALSE; // tidak ada data yang dicari... no duplicate		
	}
    
    public function delete($id){
        $q[] = "
        DELETE FROM `caramel_managerial`.`user_account` 
        WHERE `id`='$id'";
        
        $q[] = "
        DELETE FROM `caramel_managerial`.`user_role` 
        WHERE `account_id`='$id'";
        
        foreach($q as $query){
            $this->db->query($query);
        }
    }
}
?>